var wxqqmap = require('./utils/qqmap-wx-jssdk.js');
var qqmapsdk = new wxqqmap({
  key: 'CTXBZ-SAQKR-ZZAWJ-WVI5N-XUHJZ-HCF5U'
});

App({
  onLaunch: function () {
    var that = this;
    wx.login({
      success: function (res) {
        var code = res.code;
        if (code) {
          //发起网络请求
          wx.getUserInfo({
            withCredentials: true,
            success: function (res_user) {
              var jsonData = {
                code: code,
                encryptedData: res_user.encryptedData,
                iv: res_user.iv
              };
              that.JsonPost('Api/User/login', jsonData, function (data) {
                console.log(data);
                if (data.mobile == null || data.identity == null || data.real_name == '') {
                  wx.setStorageSync("certification", "false");
                } else {
                  wx.setStorageSync("certification", "true");
                }
                //存储用户信息
                wx.setStorageSync("userId", data.id);
                wx.setStorageSync("userName", data.user_name);
                wx.setStorageSync("realName", data.real_name);
                wx.setStorageSync("identity", data.identity);
                wx.setStorageSync("avatar", data.avatar);
                wx.setStorageSync("gender", data.gender);
                wx.setStorageSync("credit", data.credit);
                wx.setStorageSync("mobile", data.mobile == null ? '' : data.mobile);
                wx.setStorageSync("wxid", data.weixin == null ? '' : data.weixin);
              })
            },
            fail: function () {
              //获取用户信息失败后，跳转授权页面
              wx.showModal({
                title: '警告',
                content: '尚未进行授权，请点击确定跳转到授权页面进行授权。',
                complete: function () {
                  wx.redirectTo({
                    url: '../tologin/tologin?code=' + code,
                  })
                }
              })
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      },
      fail: function () {
        console.log('登陆失败！')
      }
    });
  },

  JsonPost: function (url, data, cb) {
    data.ajax = 1;
    if (wx.getStorageSync("userId") !== '') {
      if (!data.user_id) {
        data.user_id = wx.getStorageSync("userId");
      }
    }
    console.log(data);
    wx.request({
      url: "https://www.saixingchi.com/" + url,
      data: data,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res);
        if (res.data.code == 200) {
          cb(res.data.data);
        } else {
          cb(false);
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  isTelphone: function (mobile) {
    var myreg = /^((13|14|15|17|18)+\d{9})$/;
    if (!myreg.test(mobile)) {
      return false;
    } else {
      return true;
    }
  },
  showLoading: function (title) {
    if (!title) {
      title = "数据加载中...请稍后...";
    }
    wx.showLoading({
      title: title,
    })
  },
  closeLoading: function () {
    wx.hideLoading()
  },
  formatNumber: function (n) {
    n = n.toString()
    return n[1] ? n : '0' + n
  },
  formatTime: function (nbr, format) {
    var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
    var returnArr = [];

    var date = new Date(nbr * 1000);
    returnArr.push(date.getFullYear());
    returnArr.push(this.formatNumber(date.getMonth() + 1));
    returnArr.push(this.formatNumber(date.getDate()));

    returnArr.push(this.formatNumber(date.getHours()));
    returnArr.push(this.formatNumber(date.getMinutes()));
    returnArr.push(this.formatNumber(date.getSeconds()));

    for (var i in returnArr) {
      format = format.replace(formateArr[i], returnArr[i]);
    }
    return format;
  },
  htmldecode: function (str) {
    var s = "";
    if (str.length == 0) return "";
    s = str.replace(/&amp;/g, "&");
    s = s.replace(/&lt;/g, "<");
    s = s.replace(/&gt;/g, ">");
    s = s.replace(/&nbsp;/g, " ");
    s = s.replace(/&#39;/g, "\'");
    s = s.replace(/&quot;/g, "\"");

    //s = s.replace(/\/upload\/ueditor/g, "https:\/\/dk.9ok.xin\/upload\/ueditor");
    return s;
  },
  timeDiff: function (date1, date2) {
    var s = '';
    var date3 = (date2 - date1) * 1000;
    var days = Math.floor(date3 / (24 * 3600 * 1000));
    var leave1 = date3 % (24 * 3600 * 1000);
    var hours = Math.floor(leave1 / (3600 * 1000));
    var leave2 = leave1 % (3600 * 1000);
    var minutes = Math.floor(leave2 / (60 * 1000));
    if (days == 0) {
      s = hours + "小时" + minutes + "分"
    } else {
      s = days + "天" + hours + "小时" + minutes + "分"
    }
    return s;
  },
  timeContrast: function (date) {
    var d = (date * 1000) - new Date().getTime();

    if (d > 0) {
      return true;
    } else {
      return false;
    }
  },
  getLocation: function (func) {
    var cb = {
      "lng": 0,
      "lat": 0,
      "province": "",
      "city": ""
    };
    qqmapsdk.reverseGeocoder({
      success: function (res) {
        cb.province = res.result.ad_info.province;
        cb.city = res.result.ad_info.city;
        cb.lng = res.result.ad_info.location.lng;
        cb.lat = res.result.ad_info.location.lat;
        func(cb);
      }
    })

  }
})